package com.vvv.shortlink.project.interceptor;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.vvv.shortlink.common.convention.excepton.ClientException;
import com.vvv.shortlink.common.dto.UserInfoDTO;
import com.vvv.shortlink.common.toolkit.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shardingsphere.distsql.parser.autogen.KernelDistSQLStatementParser;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

/**
 * @author vvv
 * @date 2024/3/1 15 01
 * discription 这个拦截器是迫不得已，因为有效接口是绕过网关的，所以只能用这个
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    public static final String LOGIN_USERINFO_KEY = "short-link:login:user_info:";

    public UserInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Long id = trying2ParseUserId(request);
        UserInfoDTO userInfoDTO = UserInfoDTO.builder()
                .id(id)
                .build();
        UserContext.saveUser(userInfoDTO);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserContext.removeUser();
    }

    private Long trying2ParseUserId(HttpServletRequest request) {
        Long id = null;
        try {
            // 获取请求参数
            String userId = request.getParameter("userId");
            if (StringUtils.isNotEmpty(userId)) {
                id =  Long.valueOf(userId);
            }
            // 请求token
            String token = request.getHeader("token");
            Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(LOGIN_USERINFO_KEY + token);
            // 未登录
            if (!userMap.isEmpty()) {
                id =  Long.valueOf((String) userMap.get("id"));
            }
        } catch (Exception e) {
            log.error(e.toString());
        }
        return id;
    }
}
